import { Button, Card,message, Table,Image,Modal,Input,Form,Upload} from "antd";
import  { useEffect, useState } from "react";
import { PlusOutlined, FormOutlined, DeleteOutlined,LoadingOutlined} from "@ant-design/icons";
import { ColumnsType } from "antd/lib/table";
import { useForm } from "antd/lib/form/Form";
import type {TrademarkData} from "@api/trademark/trademark"
import {remove,addOrUpdate,getPageListInfo} from "@api/trademark/trademark"

//暴露一个TradeMark函数组件
export default function TradeMark() {
  // table-header
   let columns : ColumnsType<any> = [
    {
      title:'序号',
      dataIndex:'id',
      width:80,
      align:'center',
      render:(x:any , y:any , index: number) => {
        return index + 1 ;
      }
    },
    {
      title:"品牌名称" ,
      dataIndex:"tmName",
      align:'center',
    },
    {
      title:"品牌Logo" ,
      // dataIndex:"logoUrl",
      align:'center',
      render:(row:TrademarkData) => {
          return <Image src={row.logoUrl}  width={100} ></Image>
      }
    },
    {
      title:"品牌操作" ,
      fixed: 'right',
      align:'center',
      render:(row:TrademarkData ) => {
        return <div>
          <Button 
          icon={<FormOutlined />} 
          type="primary" style={{margin:10}}
          onClick = {showaupdata(row)}
          >修改</Button>

          <Button 
          icon={ <DeleteOutlined />} 
          type="primary" danger  
          onClick= { () => {
            removeTradeMarkItem(row)
          } }
          >删除</Button>
        </div>
      }
    },
  ];

  // Page 初试值
  const [current , setCurrent] = useState(1); //当前页
  const [pageSize , setpageSize] = useState(5); //每页显示数量
  const [total , setTotal] = useState(100); //总条数
  //创建的 form 控制实例
  const [form] = useForm()
  //设置加载中的状态
  const [loading, setLoading] = useState(false);
  //设置商品列表初始值
  const [trademarkData, setTrademarkData] = useState<TrademarkData[]>([]);
  //每一项商品初始值
  const [trademark, setTrademark] = useState<TrademarkData>({id:"",tmName:'',logoUrl:''});

  //获取商品列表
  const getTrademarkList = async (page=current, limit=pageSize) => {
    try{
      setLoading(true);
      let result = await getPageListInfo(page,limit);
      console.log(result)
      setLoading(false);
      //保存数据
      setTrademarkData(result.records);
      //设置分页的总数
      setTotal(result.total);
    }catch(e){
      message.error('请求失败~~');
    }
  }
  //添加或修改某一商品 点击确定时发送请求
  const addOrUpdateTdmItem =  async () => {
  try{
    setLoading(true);
    await addOrUpdate(trademark);
    // getTrademarkList()
    // getTrademarkList( trademark.id ? current : 1)
    if(trademark.id){
      getTrademarkList(current)
    }else{
      getTrademarkList(1)
      setCurrent(1) 
    }
    setLoading(false);
  }catch(e){
    message.error("请求失败")
  }
  }

  //点击修改回显数据 点击确定时发送请求
  const showaupdata = (row:TrademarkData) => {
   return () => {
      setIsModalOpen(true);
      const trademark = {...row }
      form.setFieldValue("tmName",row.tmName)
      setTrademark({
        id:trademark.id,
        tmName:trademark.tmName,
        logoUrl:trademark.logoUrl
      })
    }
}

  // 删除某一商品
  const removeTradeMarkItem = async (row:TrademarkData) => {
      try{
        await remove(row.id as number)
        message.success("删除成功")
        getTrademarkList( trademarkData.length > 1? current : current-1)
      }catch(error) {
        message.error("删除失败")
      }
  }

  //通过input 应用onChange事件 给trademark.tmName赋值
  const gettmName = (event:any) => {
    setTrademark({
      ...trademark ,
      tmName : event.target.value
    }) 
  }

  useEffect(() => {
    //调用函数获取列表数据
    getTrademarkList();
  }, [current, pageSize]);
   
    const [isModalOpen, setIsModalOpen] = useState(false);
    //点击添加显示对话框
    const showModal = () => {
      form.resetFields()
      setTrademark({
        id:"",
        tmName:"",
        logoUrl:""
      })

      setIsModalOpen(true);
    };
    //对话框点击确定
    const handleOk = async () => {
      // setIsModalOpen(false);
      // console.log(trademark.tmName)
      // console.log(trademark.logoUrl)
      try {
        await form.validateFields(["tmName","logoUrl"])
        setIsModalOpen(false);
        addOrUpdateTdmItem()
        getTrademarkList()
      } catch (error) {
        message.error("请填写正确信息")
      }
    };
    //对话框点击取消
    const handleCancel = () => {
      setIsModalOpen(false);
    };

  //upload 1
  const getBase64 = (img:any, callback:any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  

  const beforeUpload = (file:any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
  
    const isLt2M = file.size / 1024 / 1024 < 2;
  
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
  
    return isJpgOrPng && isLt2M;
  }
 
  //upload 2
  const [imageUrl, setImageUrl] = useState("");
  //通过Upload 应用onChange事件 给trademark.logoUrl赋值
  const handleChange = (info:any) => {
  console.log(info)
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url:any) => {
        setLoading(false);
      // setImageUrl(url);
      //此时 trademark 中 有tmName 和 logoUrl 回显
        setTrademark({
          ...trademark,
          logoUrl: info.file.response.data
        })
      });
    }
  };
  
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传图片
      </div>
    </div>
  );

  // table-show
   return(
     <Card>

        <Button icon={<PlusOutlined />} 
        type="primary"
        style={{marginBottom:30}}
        onClick = {showModal}
        >添加</Button>
        
        <Table
          columns={columns}
          bordered
          scroll={{x: 1200}}
          rowKey='id'
          loading={loading}
          dataSource={trademarkData}
          pagination = {{
            current : current ,
            pageSize : pageSize ,
            total : total ,
            showQuickJumper : true ,
            pageSizeOptions : [3,5,10,20],
            showSizeChanger : true ,
            showTotal : () => {
              return <span>总计:{total}</span>
            },
            onChange : (page: number, pageSize: number) => {
               setCurrent(page);
               setpageSize(pageSize);
            }
          }}
        >
        </Table> 
        
        <>
        {/* 对话框 */}
        <Modal title="添加品牌" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form 
         size="middle"
         labelCol={{ span: 4 }}
         wrapperCol={{ span: 16 }}
         initialValues={{}}
         autoComplete="off"
         form={form}
        >
        
        <Form.Item
        label="品牌名称"
        name="tmName"
        rules={[{ required: true, message: '品牌名称必须输入'},
                {min:2,max:10,message: '品牌名称必须在2~10直接'}
      ]}
      >  
        <Input value={trademark?.tmName}  onChange={gettmName} />  
        {/* 通过input输入框 获取用户输入的值 */}
      </Form.Item>
          
        <Form.Item
        label="品牌LOGO"
        name="logoUrl"
        valuePropName="fileList"
        // rules={[{ required: true, message: '必须上传图片' }]}
        >
          <>
          <Upload
              listType="picture-card"
              showUploadList={false}
              action="/dev-api/admin/product/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            > 
              {/* 判断图片是不是上传成功 成功回显时 显示该图片 */}
              {trademark.logoUrl ? (
                <img
                  src={trademark.logoUrl}
                  alt="avatar"
                  style={{
                    width: '100%',
                  }}
                />
              ) : (
                uploadButton
              )}
          </Upload>
  
          </>
        </Form.Item>

        </Form>
        </Modal>
        </>
     </Card>
   )
}


